package com.song.service.impl.school;

import com.song.entity.school.Student;
import com.song.enums.GenderEnum;
import com.song.mapper.school.StudentMapper;
import com.song.service.school.StudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.song.util.excel.EasyPoiUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFPictureData;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 学生信息 服务实现类
 * </p>
 *
 * @author song
 * @since 2024-11-29
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Override
    public List<Student> importList(MultipartFile file) {
        try {
            List<Student> studentList = new ArrayList<>();
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
            XSSFSheet sheet = workbook.getSheetAt(0);
            Map<String, Map<String, XSSFPictureData>> rowMap = EasyPoiUtil.parsePictures(sheet);
            for (Row row : sheet){
                if (row.getRowNum() == 0){
                    continue;
                }
                Student student = new Student();
                student.setXm(row.getCell(0).getStringCellValue());
                student.setXb(GenderEnum.getGenderCode(row.getCell(1).getStringCellValue()));
                student.setXh(row.getCell(2).getStringCellValue());
                student.setSfzh(row.getCell(3).getStringCellValue());
                student.setCsrq(row.getCell(4).getLocalDateTimeCellValue().toLocalDate());
                if (!rowMap.containsKey(String.valueOf(row.getRowNum()))){
                    studentList.add(student);
                    continue;
                }
                Map<String, XSSFPictureData> colMap = rowMap.get(String.valueOf(row.getRowNum()));
                if (colMap.containsKey("5")){
                    student.setXjz(Base64.getEncoder().encodeToString(colMap.get("5").getData()));
                }
                if (colMap.containsKey("6")){
                    student.setTx(Base64.getEncoder().encodeToString(colMap.get("6").getData()));
                }
                studentList.add(student);
            }
            saveBatch(studentList);
            return studentList;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
